<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/30
 * Time: 22:47
 */

namespace app\company\controller;


use app\common\controller\Comm;
use app\common\model\BusInquiry;
use app\common\model\BusInquiryDetail;
use app\common\model\BusInquiryDetailSupplier;
use app\common\model\BusInquirySuppliers;
use app\common\model\SalesCompany;
use app\common\model\SuppliersCompany;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class Inquiry extends Comm
{
    protected $quiltyField = [
        'qulity_service_price',
        'qulity_org_price',
        'qulity_matching_price',
        'qulity_complete_price',
        'qulity_suitable_price'
    ];
    /**
     * 获取公司列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList(){
        $inquiryModel = new BusInquiry();
        $inquiryModel->where(['deadline_datetime'=>['<',date('Y-m-d H:i:s')],'sale_price_state'=>0])->setField('state',3);
        $page = input('page', 1);
        $limit = input('limit', 20);
        $due_date = input('due_date','');
//        $words = input('words','','trim');
        $company_id = input('opt_user_id','','trim');
        $bus_inquiry_no = input('bus_inquiry_no','','trim');
        $vehicle_frame_no = input('vehicle_frame_no','','trim');
        $vehicle_license_num = input('vehicle_license_num','','trim');
        $car_model = input('car_model','','trim');
        $service_no = input('service_no','','trim');
        $bus_from_company_name = input('bus_from_company_name','','trim');
        $state = input('state','','trim');
        $is_expired = input('is_expired','','trim');
        $add_user_name = input('add_user_name','','trim');

        $param = array();

        $param['bus_to_company_id'] = $company_id;
        if($due_date){
            $date_arr = explode(' - ',$due_date);
            if(!empty($date_arr)){
                $param['add_datetime'] = ['<=', trim($date_arr[0])];
                $param['deadline_datetime'] = ['>=', date('Y-m-d', strtotime ("+1 day", strtotime(trim($date_arr[1]))))];
            }
        }
        if($bus_inquiry_no){
            $param['bus_inquiry_no'] = ['like','%'.$bus_inquiry_no.'%'];
        }
        if($vehicle_frame_no){
            $param['vehicle_frame_no'] = ['like','%'.$vehicle_frame_no.'%'];
        }
        if($vehicle_license_num){
            $param['vehicle_license_num'] = ['like','%'.$vehicle_license_num.'%'];
        }
        if($car_model){
            $param['car_model'] = ['like','%'.$car_model.'%'];
        }
        if($service_no){
            $param['service_no'] = ['like','%'.$service_no.'%'];
        }
        if($bus_from_company_name){
            $param['bus_from_company_name'] = ['like','%'.$bus_from_company_name.'%'];
        }
        if($add_user_name){
            $param['bus_user_name'] = ['like','%'.$add_user_name.'%'];
        }

        if($is_expired){
            $param['deadline_datetime'] = ['<',date('Y-m-d H:i:s')];
        }elseif ($is_expired !== ''){
            $param['deadline_datetime'] = ['>',date('Y-m-d H:i:s')];
        }


        if($state || $state !== ''){
            if($state == 2){
                $param['state'] = ['in',[2,5,6]];
            }else{
                $param['state'] = $state;
            }
        }



        /*if($words){
            $param['bus_inquiry_no|vehicle_frame_no|vehicle_license_num|car_series|car_model|brand_name|service_no|bus_to_company_name|bus_from_company_name'] = ['like','%'.$words.'%'];
        }*/

        $model = new BusInquirySuppliers();

        $count = $model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $model->with(['sales_company','detailNum','inquiry'])->where($param)->order('add_datetime desc,id desc')->page($page,$limit)->select();
        $times = date('Y-m-d H');
        foreach ($lst as $item){
            $item['is_expired'] = $item['deadline_datetime']<$times ? 1 :0;
        }
        return json_tab_msg($count,$page,$lst);
    }


    /**
     * 获取单个供货商信息
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getInfo(){
        $id = input('id');
        $model = new BusInquirySuppliers();
        $detail_model = new BusInquiryDetailSupplier();
        $info = $model->with(['inquiry','detailInfo'=>function ($query) {
            $query->with('detailCommon');
        }])->where(['id'=>$id])->find()->toArray();
//        $info['detail_info'] = $detail_model->with('detailCommon')->where(['bus_inquiry_suppliers_id'=>$id])->select();
        $sum_info = $detail_model->field('sum(num) as num,sum(qulity_service_price) as qulity_service_price,sum(qulity_org_price) as qulity_org_price,sum(qulity_matching_price) as qulity_matching_price,sum(qulity_complete_price) as qulity_complete_price,sum(qulity_suitable_price) as qulity_suitable_price')->where(['bus_inquiry_suppliers_id'=>$id])->find();
        $add_arr = [
            [
                'id'=>-1,
                'eq_name'=>'合计',
                'num'=>$sum_info['num'],
                'qulity_service_price'=>$sum_info['qulity_service_price'],
                'qulity_org_price'=>$sum_info['qulity_org_price'],
                'qulity_matching_price'=>$sum_info['qulity_matching_price'],
                'qulity_complete_price'=>$sum_info['qulity_complete_price'],
                'qulity_suitable_price'=>$sum_info['qulity_suitable_price'],
            ],
        ];
        $info['detail_info'] = array_merge($info['detail_info'], $add_arr);
        json_return_code($info);
    }


    public function editContent()
    {
        $data = $this->trimParam();
        $detailModel = new BusInquiryDetailSupplier();
        $up_data[$data['tag_name']] = $data['value'];

        $detailModel->startTrans();
        $spplierModel = new BusInquirySuppliers();
        $inquiryDetailModel = new BusInquiryDetail();
        try {
            if(in_array($data['tag_name'],$this->quiltyField)){
                $up_data['state'] = 2;
                $spplierModel->where(['id'=>$data['bus_inquiry_suppliers_id']])->setField('state',1);
            }
            /*if($data['tag_name'] == 'oe_no'){
                $inquiryDetailModel->where(['id'=>$data['bus_inquiry_detail_id']])->setField('oe_no',$data['value']);
                $detailModel->where(['bus_inquiry_detail_id'=>$data['bus_inquiry_detail_id']])->setField('oe_no',$data['value']);
            }*/
            $detailModel->isUpdate(true)->save($up_data,['id'=>$data['id']]);
            $detailModel->commit();
            addLog('修改询价单价格');
            json_return_code();
        }catch (Exception $e){
            $detailModel->rollback();
            json_return_code('','操作失败',201);
        }
    }

    /**
     * 放弃报价
     * @return void
     */
    public function abandonInquiry()
    {
        $id = input('id');
        $data['common_giveup'] = input('common','','trim');
        $data['state'] = 4;
        $model = new BusInquirySuppliers();
        if($model->isUpdate(true)->save($data,['id'=>$id]) !== false){
            addLog('放弃报价');
            json_return_code('成功');
        }else{
            json_return_code('','提交失败',201);
        }

    }
    /**
     * 报价
     * @return \think\response\Json
     */
    public function quoteInquiry(){
        $data = $this->trimParam();
        $model = new BusInquirySuppliers();
        $detailModel = new BusInquiryDetailSupplier();
        $bus_inquiry_suppliers_id = $data['id'];
        $times = date('Y-m-d H:i:s');
        $inquiry_data = [
            'state'=>2,
            'update_time'=>$times
        ];
        $model->startTrans();
        try{
            $model->isUpdate(true)->save($inquiry_data,['id'=>$bus_inquiry_suppliers_id]);
            //处理详情表数据
            $detail_add_arr = [
                'state'=>3,
            ];
            $con['qulity_service_price|qulity_org_price|qulity_matching_price|qulity_complete_price|qulity_suitable_price']= ['>',0];
            $con['bus_inquiry_suppliers_id']= $bus_inquiry_suppliers_id;
            $detailModel->isUpdate(true)->save($detail_add_arr,$con);
            // $detailModel->isUpdate(true)->save($detail_add_arr,['bus_inquiry_suppliers_id'=>$bus_inquiry_suppliers_id,'state'=>2]);
            $model->commit();
            addLog('提交报价');
            json_return_code();
        }catch (Exception $e){
            $model->rollback();
            json_return_code('','提交失败'.$e->getMessage(),201);
        }
    }
    public function quoteInquiry1(){
        $data = $this->trimParam();
        $model = new BusInquirySuppliers();
        $detailModel = new BusInquiryDetailSupplier();
        $bus_inquiry_id = $data['id'];
        $detail_info = $data['detail_info']; // 详情
        $times = date('Y-m-d H:i:s');
        $inquiry_data = [
            'state'=>2,
            'update_time'=>$times
        ];
        $model->startTrans();
        try{
            $model->isUpdate(true)->save($inquiry_data,['id'=>$bus_inquiry_id]);
            //处理详情表数据
            $detail_add_arr = [
                'state'=>3,
            ];
            $detail_info = array_map(function($item) use ($detail_add_arr) {
                return array_merge($item, $detail_add_arr);
            }, $detail_info);
            $detailModel->allowField(['state','qulity_service_price','qulity_org_price','qulity_matching_price','qulity_complete_price','qulity_suitable_price'])->saveAll($detail_info);
            $model->commit();
            $inquiry_data['id'] = $bus_inquiry_id;
            $inquiry_data['detail_info'] = $detail_info;
            json_return_code($inquiry_data);
        }catch (Exception $e){
            $model->rollback();
            json_return_code('','提交失败'.$e->getMessage(),201);
        }
    }

    /**
     * 修改供货商状态
     * @return void
     */
    public function changeState()
    {
        $id = input('id');
        $data['state'] = input('state');
        $model = new BusInquiry();
        if($model->isUpdate(true)->save($data,['id'=>$id]) !== false){
            addLog('修改供货商状态');
            json_return_code();
        }else{
            json_return_code('','操作失败',201);
        }
    }

}